import logging
import os
import uvicorn
from contextlib import asynccontextmanager
from dotenv import load_dotenv
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse

from tortoise.contrib.fastapi import register_tortoise

from controller.qwen3_controller import qwen3
from controller.rag_controller import rag
from exception.all_exception import global_exception_handlers

from controller.pyttsx3_contrller import router
from service.pyttsx3_service import TTSService



@asynccontextmanager
async def lifespan(_app: FastAPI):
    # 启动时执行
    os.makedirs("logs", exist_ok=True)

    # 清除旧的 handler，防止重复添加
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)

    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(levelname)s - %(message)s",
        handlers=[
            logging.FileHandler("logs/app.log", mode='a', encoding='utf-8'),
            logging.StreamHandler()
        ]
    )
    logging.info("fastapi run------------------ Starting")

    yield

    # 关闭时执行
    logging.info("fastapi run------------------ ending")


def create_app():
    _app = FastAPI(
        title="digital portrait service",
        version="v1.0.1",
        # 全局以及自定义异常捕获
        exception_handlers=global_exception_handlers,
        lifespan=lifespan
    )
    _app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    _app.mount("/static",StaticFiles(directory="dist"),name="static")

    @_app.get("/")
    async def index():
        return FileResponse("dist/index.html")
    # 添加路由
    # _app.include_router(router=router, prefix="/v1/router", tags=["router"])
    # _app.include_router(router=router,prefix="/api/tts",tags=["router"])
    _app.include_router(router=qwen3,prefix="/v1/qwen3", tags=["qwen3"])
    _app.include_router(router=rag, prefix="/v1/rag", tags=["rag"])
    _app.include_router(router=router, prefix="/v1/x3", tags=["tags"])


    load_dotenv()
    # 数据库连接
    database_username = os.getenv("SQL_USERNAME")
    database_password = os.getenv("SQL_PASSWORD")
    database_host = os.getenv("SQL_HOST")
    database_port = os.getenv("SQL_PORT")
    database_name = os.getenv("SQL_DATABASE")
    register_tortoise(
        _app,
        db_url=f"mysql://{database_username}:{database_password}@{database_host}:{database_port}/{database_name}",
        modules={'models': ['entity.database.mysql']},  # 替换成你定义的模型路径
        generate_schemas=False,  # 若首次初始化需要建表可打开
        add_exception_handlers=True,
    )

    return _app

# app = create_app()  # 正式环境切换

if __name__ == '__main__':
    app = create_app()
    uvicorn.run(app, host=os.environ.get('SERVER_HOST', '0.0.0.0'), port=int(os.environ.get('SERVER_PORT', 8000)))
